<?php

class PurchaseController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $session = new Zend_Session_Namespace('Zend_Auth');
        $this->sess = $session->data;

        if(!isset($this->sess)){
            $param = array(
            'action' => 'login',
            'controller' => 'index',
            'msg' => 'Session Timeout silahkan login kembali !'
            );
            $this->_redirect($this->view->url($param, 'default', true));
        }
        
        $this->_helper->layout->setLayout('purchase');

        $this->request = $this->getRequest();
        $this->param = $this->request->getParams();

        $this->member = new Application_Model_Member();
        $newMembers = $this->member->getNewMembers(20);
        $this->view->newMembers = $newMembers;

        $rewardMember = $this->member->getRewardMembers(20);
        $this->view->rewardMember = $rewardMember;

    }

    public function indexAction()
    {
        // action body
        //if (Zend_Auth::getInstance()->hasIdentity() && isset($session->data)) {
        

        $this->view->msg = (isset($this->param['msg'])) ? $this->param['msg'] : "";
    }
    
    public function cellphonebuyAction(){

        $modelPurchase = new Application_Model_Purchase();

        if ($this->getRequest()->isPost()) {

            $this->_helper->layout->disableLayout();
            $formData = $this->_request->getPost();

            $voucherCode = $formData['voucherCode'];
            $phone = $formData['no_celluler'];
            $remark = $formData['remark'];
            $act = 'PULSA';

            //Cek saldo
            $modelRek = new Application_Model_Rekening();
            $dataRek = $modelRek->getTotalBalance($this->sess->member_code);
            $balance = $dataRek["balance_trx"];

            $dataVoucher = $modelPurchase->getVoucherByCode($voucherCode);
            $hargaVoucher = $dataVoucher["price"];

            if ($balance >= $hargaVoucher){
            
                $modelMember = new Application_Model_Member();
                $dataMember = $modelMember->getMemberDetail($this->sess->member_id);

                // new HTTP request to some HTTP address
                $client = new Zend_Http_Client('http://api.keajaibancbr.com/');
                // set some parameters

                $client->setParameterPost(array(
                    'act' => $act,
                    'sn' => $this->sess->member_code,
                    'pin' => $this->sess->pin,
                    'msisdn' => $dataMember['mobile_no'],
                    'reffNo' => $phone,
                    'product' => $voucherCode,
                    'ket' => $remark,
                    'btnSubmit' => 'Submit'
                ));

                // POST request
                $response = $client->request(Zend_Http_Client::POST);

                //Dump headers
                //print_r($response->headers);

                //Dump body
                //print_r($response->getBody());

                $resp = json_decode($response->getBody());

                $code = $resp->code;
                $msg = $resp->msg;

                if($code == '0'){
                        $this->view->code = $code;
                        $this->view->msg = 'Pembelian Voucher Seluler/PLN Berhasil diantrikan';
                }else{
                    $this->view->code = '1';
                    $this->view->msg = "ERROR ".$msg;
                }

                //die();
            }else{

                $this->view->code = '1';
                $this->view->msg = "ERROR Maaf Saldo anda tidak mencukupi.";

            }
        
        }else{

            $op = $modelPurchase->getOperatorList();            
            $this->view->op = $op;            

            $accNum = $this->sess->member_code;
            $modelAcc = new Application_Model_Rekening();
            $accountList = $modelAcc->getAccounts($accNum);

            $modelFunc = new Application_Model_Functions();
            $this->view->today =  $modelFunc->gatDayIndoName(date('l')).', '.date('d F Y H:i:s');
            $this->view->accountList = $accountList;

        }
        
    }

    public function cellphonepayAction(){

        $memberId = $this->sess->member_id;
        $accNum = $this->sess->member_code;
        
        if ($this->getRequest()->isPost()) {

            $this->_helper->layout->disableLayout();
            $formData = $this->_request->getPost();

            
            $fromAcc = $formData['fromAcc'];
            $payFor = $formData['pay_for'];
            $toAcc = (isset($formData['from_list'])) ? $formData['from_list'] : "";
            $toOtherAcc = (isset($formData['no_phonecell'])) ? $formData['no_phonecell'] : "";
            $cbSave = (isset($formData['cbSave'])) ? $formData['cbSave'] : "";
            $saveAs = (isset($formData['saveAs'])) ? $formData['saveAs'] : "";            
            $remark = $formData['remark'];
            $act = $formData['act']; //'BYR';
            

            $step = ($act == 'TAG') ? 1 : 2;

            //Inquiry Tagihan
            if ($act == 'TAG'){
                
                $fromRadio = $formData['fromRadio'];
                $idPelanggan = ($fromRadio == 1) ? $toAcc : $toOtherAcc;
                
                $modelMember = new Application_Model_Member();
                $dataMember = $modelMember->getMemberDetail($memberId);

                // new HTTP request to some HTTP address
                $client = new Zend_Http_Client('http://api.keajaibancbr.com');
                // set some parameters

                $client->setParameterPost(array(
                    'act' => $act,
                    'sn' => $accNum,
                    'pin' => $this->sess->pin,
                    'msisdn' => $dataMember['mobile_no'],
                    'product' => $payFor,
                    'reffNo' => $idPelanggan,
                    'ket' => $remark,
                    'orderId' => '',
                    'btnSubmit' => 'Submit'
                ));


                // POST request
                $response = $client->request(Zend_Http_Client::POST);

                $resp = json_decode($response->getBody());

                $code = $resp->code;
                $msg = $resp->pesan;

                $formData['idPelanggan'] = $idPelanggan;
                $this->view->data = $resp;
                $this->view->formData = $formData;

                $this->view->step = $step;
                $this->view->code = $code;

                if($code == '0'){                        

                    //Jika disave
                    if ($cbSave != ""){
                        $dataTrans = array(
                            'phone_num' => $toOtherAcc,
                            'member_id' => $memberId,
                            'trans_name' => $saveAs,
                            'trans_type_id' => 21
                            );

                        $modelTransfer = new Application_Model_Transfer();
                        $save = $modelTransfer->saveToPersonalTrans($dataTrans);
                    }

                    //$this->view->msg = 'Bayar Tagihan Telepon/Seluler/PLN Berhasil diantrikan';

                    $modelAcc = new Application_Model_Rekening();
                    $accountList = $modelAcc->getAccounts($accNum);
                    $this->view->accountList = $accountList;
                        

                }else{
                    $this->view->code = '1';
                    $this->view->msg = "ERROR ".$msg;
                }


            }else{  //Proses Pembayaran

                $jmlBayar = $formData['jml_bayar'];
                $idPelanggan = $toOtherAcc;

                //Cek saldo
                $modelRek = new Application_Model_Rekening();
                $dataRek = $modelRek->getTotalBalance($this->sess->member_code);
                $balance = $dataRek["balance_trx"];

                //Cek saldo
                if($balance >= $jmlBayar){

                    $modelMember = new Application_Model_Member();
                    $dataMember = $modelMember->getMemberDetail($memberId);

                    // new HTTP request to some HTTP address
                    $client = new Zend_Http_Client('http://api.keajaibancbr.com');
                    // set some parameters

                    $client->setParameterPost(array(
                        'act' => $act,
                        'sn' => $accNum,
                        'pin' => $this->sess->pin,
                        'msisdn' => $dataMember['mobile_no'],
                        'product' => $payFor,
                        'reffNo' => $idPelanggan,
                        'amount' => $jmlBayar,
                        'ket' => $remark,
                        'orderId' => '',
                        'btnSubmit' => 'Submit'
                    ));


                    // POST request
                    $response = $client->request(Zend_Http_Client::POST);

                    $resp = json_decode($response->getBody());

                    $code = $resp->code;
                    $msg = $resp->msg;

                    $this->view->step = $step;
                    $this->view->code = $code;

                    if($code == '0'){

                        $this->view->msg = 'Pembayaran Tagihan Telepon/Seluler/PLN Berhasil diantrikan';

                    }else{
                        $this->view->code = '1';
                        $this->view->msg = "ERROR ".$msg;
                    }

                }else{

                    $this->view->code = '1';
                    $this->view->msg = "ERROR Maaf Saldo anda tidak mencukupi.";

                }

            }

        }else{
            
            $modelAcc = new Application_Model_Rekening();
            $accountList = $modelAcc->getAccounts($accNum);

            $modelFunc = new Application_Model_Functions();
            $this->view->today =  $modelFunc->gatDayIndoName(date('l')).', '.date('d F Y H:i:s');
            $this->view->accountList = $accountList;
            $this->view->act = '';

            //$accPersonalList = $modelAcc->getPersonalAcc($memberId, "trans_type_id = 21");
            //$this->view->accPersonalList = $accPersonalList;
        }

    }


    public function plnpayAction(){

        $memberId = $this->sess->member_id;
        $accNum = $this->sess->member_code;

        if ($this->getRequest()->isPost()) {

            $this->_helper->layout->disableLayout();
            $formData = $this->_request->getPost();


            $fromAcc = $formData['fromAcc'];
            $fromRadio = $formData['fromRadio'];
            $toAcc = (isset($formData['from_list'])) ? $formData['from_list'] : "";
            $toOtherAcc = (isset($formData['no_pln'])) ? $formData['no_pln'] : "";
            $cbSave = (isset($formData['cbSave'])) ? $formData['cbSave'] : "";
            $saveAs = (isset($formData['saveAs'])) ? $formData['saveAs'] : "";
            $remark = $formData['remark'];
            $act = 'BYR';

            $idPelanggan = ($fromRadio == 1) ? $toAcc : $toOtherAcc;

                //$sn1, $msisdn, $product, $idPelanggan

            $modelMember = new Application_Model_Member();
            $dataMember = $modelMember->getMemberDetail($memberId);

            // new HTTP request to some HTTP address
            $client = new Zend_Http_Client('http://api.keajaibancbr.com/');
            // set some parameters

            $client->setParameterPost(array(
                'act' => $act,
                'sn' => $accNum,
                'msisdn' => $dataMember['mobile_no'],
                'productId' => $idPelanggan,
                'productCode' => 'PLN',
                'ket' => $remark

            ));

            // POST request
            $response = $client->request(Zend_Http_Client::POST);

            $code = $response['code'];
            $msg = $response['msg'];

            if($code == 0){
                    //Jika disave
                    if ($cbSave != ""){
                        $dataTrans = array(
                            'phone_num' => $toOtherAcc,
                            'member_id' => $memberId,
                            'trans_name' => $saveAs,
                            'trans_type_id' => 22
                            );

                        $modelTransfer = new Application_Model_Transfer();
                        $save = $modelTransfer->saveToPersonalTrans($dataTrans);
                    }

                    $this->view->code = $code;
                    $this->view->msg = $msg;
            }else{
                $this->view->code = '1';
                $this->view->msg = "ERROR ".$msg;
            }


        }else{

            $modelAcc = new Application_Model_Rekening();
            $accountList = $modelAcc->getAccounts($accNum);

            $modelFunc = new Application_Model_Functions();
            $this->view->today =  $modelFunc->gatDayIndoName(date('l')).', '.date('d F Y H:i:s');
            $this->view->accountList = $accountList;

            $accPersonalList = $modelAcc->getPersonalAcc($memberId, "trans_type_id = 22");
            $this->view->accPersonalList = $accPersonalList;
        }

    }

    public function paylistAction(){

        $memberId = $this->sess->member_id;
        $accNum = $this->sess->member_code;

        if ($this->getRequest()->isPost()) {

            $this->_helper->layout->disableLayout();
            $formData  = $this->_request->getPost();


            $fromAcc = $formData['fromAcc'];
            $toRadio = $formData['toRadio'];
            $toAcc = (isset($formData['toAcc'])) ? $formData['toAcc'] : "";
            $toOtherAcc = (isset($formData['toOtherAcc'])) ? $formData['toOtherAcc'] : "";
            $cbSave = (isset($formData['cbSave'])) ? $formData['cbSave'] : "";
            $saveAs = (isset($formData['saveAs'])) ? $formData['saveAs'] : "";
            $amount = $formData['amount'];
            $remark = $formData['remark'];

            $toAcc = ($toRadio == 1) ? $toAcc : $toOtherAcc;



            $errorMsg = "";


            $accModel = new Application_Model_Rekening();
            //Pastikan Balance
            $getBalance = $accModel->getTotalBalance($fromAcc);
            $balance = $getBalance["balance"];

            if ($amount > $balance){
                $errorMsg .= "* Jumlah Transfer lebih besar daripada jumlah saldo.<br>";
            }


            //cek minimum saldo
	    /*if ($minSaldo > $balance || $minSaldo > ($balance - ($transfer+$biaya))){
                $this->view->errorMsg .= "* Minimum Saldo tidak mencukupi.<br>";
                //return;
                $err = 1;
            }
             *
             */

            //
            if ($toRadio == 2){
                // Cek Account Tujuan
                $dataAcc = $accModel->isExistAccount($toOtherAcc);
                if ($dataAcc["cnt"] == 0){
                    $errorMsg .= "* Nomor Akun Tujuan tidak terdaftar.<br>";

                }
            }


            if ($errorMsg == ""){

                $modelTransfer = new Application_Model_Transfer();
                $data = $modelTransfer->transferPoint($memberId, $fromAcc, $toAcc, $amount, $remark);

                $code = $data['code'];
                $msg = $data['msg'];

                if($code == 0){
                        //Jika disave
                        if ($cbSave != ""){
                            $dataTrans = array(
                                'account_num' => $toOtherAcc,
                                'member_id' => $memberId,
                                'trans_name' => $saveAs,
                                'trans_type_id' => 0
                                );

                            $save = $modelTransfer->saveToPersonalTrans($dataTrans);
                        }

                        $this->view->code = $code;
                        $this->view->msg = $msg;
                }else{
                    $this->view->code = '1';
                    $this->view->msg = "ERROR ".$msg;
                }
            }else{
                $this->view->code = '1';
                $this->view->msg = "ERROR ".$errorMsg;
            }

        }else{
            $modelAcc = new Application_Model_Rekening();
            $accountList = $modelAcc->getAccounts($accNum);
            $accPersonalList = $modelAcc->getPersonalAcc($memberId, "trans_type_id = 0");

            $modelFunc = new Application_Model_Functions();
            $this->view->today =  $modelFunc->gatDayIndoName(date('l')).', '.date('d F Y H:i:s');
            $this->view->accountList = $accountList;
            $this->view->accPersonalList = $accPersonalList;
        }
    }

    public function trackingAction() {

        $accNum = $this->sess->member_code;
        
        
        $modelFunc = new Application_Model_Functions();
        $this->view->today = $modelFunc->gatDayIndoName(date('l')) . ', ' . date('d F Y H:i:s');
        
        $memberId = $this->sess->member_id;

        $dateTmp1 = (isset($this->param['date1'])) ? $this->param['date1'] : date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = (isset($this->param['date2'])) ? $this->param['date2'] : date('Y-m-d');

        $date1 = (isset($this->param['date1'])) ? str_replace('-', '', $this->param['date1']) : date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = (isset($this->param['date2'])) ? str_replace('-', '', $this->param['date2']) : date('Ymd');

        $arrDate = array('date1' => $date1, 'date2' => $date2, 'dateTmp1' => $dateTmp1, 'dateTmp2' => $dateTmp2);

        $this->view->data = $arrDate;

        $transTypeList = new Application_Model_TransType();
        $this->view->transTypeList = $transTypeList->transTypeListPPOB();

    }
}

